package com.sc.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sc.demo.domain.Users;
import com.sc.demo.mapper.UserMapper;
import com.sc.demo.service.MyUserDetailService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;

/**
 * @version 1.0
 * @Author: 许啸林
 * @Date: 2021/6/22 12:27
 */
@Service
public class MyUserDetailServicesImpl implements MyUserDetailService {
    @Resource       
    private UserMapper userMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Users::getUsername, username);
        Users user = userMapper.selectOne(queryWrapper);
        if(user == null) {
            throw new UsernameNotFoundException("用户不存在!");
        }
        List<GrantedAuthority> premession = AuthorityUtils.commaSeparatedStringToAuthorityList("list,ROLE_sale");
        return new User(user.getUsername(), new BCryptPasswordEncoder().encode(user.getPassword()), premession);
    }
}
